# TODO: 导入必要的库和模块
import numpy as np
from sklearn.datasets import load_digits
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import pickle
from tqdm import tqdm
import time
# TODO: 加载数字数据集
digits = load_digits()
X = digits.data
y = digits.target
# TODO: 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# TODO: 初始化变量以存储最佳准确率，相应的k值和最佳knn模型
a1 = 0
a_k = None
a_knn = None
# TODO: 初始化一个列表以存储每个k值的准确率
list =[]
# TODO: 尝试从1到40的k值，对于每个k值，训练knn模型，保存最佳准确率，k值和knn模型
linspace_list = np.linspace(0,5,100)
for element in tqdm(linspace_list, desc="提示词: ", unit="每秒的单位"):
    for k in range(1,41):
        knn = KNeighborsClassifier(n_neighbors=k)
        knn.fit(X_train,y_train)
        a = knn.score(X_test, y_test)
        x = range(41)
        y = np.cumsum(a)
        plt.plot(k,y,    # 绘制折线图
            linestyle='dashed', color='blue',    # 设置折线的样式和颜色
            marker='o',markerfacecolor='red', markersize=5)    # 设置数据点的样式，颜色和大小
        if a>a1:
            a1 = a
            a_k = k
            a_knn = knn
plt.axvline(a_k, color='r')
plt.text(a_k, a1,'k={:.2f},a1={:.2f}'.format(a_k,a1), fontsize=12)
plt.savefig("accuracy_plot.pdf")
# TODO: 将最佳KNN模型保存到二进制文件
with open('best_knn_model.pkl','wb') as f:
    pickle.dump(knn,f)
# TODO: 打印最佳准确率和相应的k值
print(a1)
print(a_k)